package forum.dao.mysql;

import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.util.concurrent.Executor;

public class MyConnectionPool implements ConnectionPool {

    private Vector<MyConnection> activeConnections = new Vector<MyConnection>();
    private Vector<MyConnection> inActiveConnections = new Vector<MyConnection>();

    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "variation";
    private static final String DB_URL = "jdbc:mysql://localhost/forum";
    private static final int MAX_CONNECTIONS = 20;

    private static class SingletonHolder {
        public static final MyConnectionPool INSTANCE = new MyConnectionPool();
    }

    private class MyConnection implements Connection {

        Connection coreConnection;

        public MyConnection(Connection connection) {
            coreConnection = connection;
        }

        @Override
        public void close() throws SQLException {
            pushback(this);
        }

        @Override
        public Statement createStatement() throws SQLException {
            return coreConnection.createStatement();
        }

        @Override
        public PreparedStatement prepareStatement(String sql) throws SQLException {
            return coreConnection.prepareStatement(sql);
        }

        @Override
        public CallableStatement prepareCall(String sql) throws SQLException {
            return coreConnection.prepareCall(sql);
        }

        @Override
        public String nativeSQL(String sql) throws SQLException {
            return coreConnection.nativeSQL(sql);
        }

        @Override
        public void setAutoCommit(boolean autoCommit) throws SQLException {
            coreConnection.setAutoCommit(autoCommit);
        }

        @Override
        public boolean getAutoCommit() throws SQLException {
            return coreConnection.getAutoCommit();
        }

        @Override
        public void commit() throws SQLException {
            coreConnection.commit();
        }

        @Override
        public void rollback() throws SQLException {
            coreConnection.rollback();
        }

        @Override
        public boolean isClosed() throws SQLException {
            return coreConnection.isClosed();
        }

        @Override
        public DatabaseMetaData getMetaData() throws SQLException {
            return coreConnection.getMetaData();
        }

        @Override
        public void setReadOnly(boolean readOnly) throws SQLException {
            coreConnection.setReadOnly(readOnly);
        }

        @Override
        public boolean isReadOnly() throws SQLException {
            return coreConnection.isReadOnly();
        }

        @Override
        public void setCatalog(String catalog) throws SQLException {
            coreConnection.setCatalog(catalog);
        }

        @Override
        public String getCatalog() throws SQLException {
            return coreConnection.getCatalog();
        }

        @Override
        public void setTransactionIsolation(int level) throws SQLException {
            coreConnection.setTransactionIsolation(level);
        }

        @Override
        public int getTransactionIsolation() throws SQLException {
            return coreConnection.getTransactionIsolation();
        }

        @Override
        public SQLWarning getWarnings() throws SQLException {
            return coreConnection.getWarnings();
        }

        @Override
        public void clearWarnings() throws SQLException {
            coreConnection.clearWarnings();
        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
            return coreConnection.createStatement(resultSetType, resultSetConcurrency);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType,
                                                  int resultSetConcurrency) throws SQLException {
            return coreConnection.prepareStatement(sql, resultSetType, resultSetConcurrency);
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            return coreConnection.prepareCall(sql, resultSetType, resultSetConcurrency);
        }

        @Override
        public Map<String, Class<?>> getTypeMap() throws SQLException {
            return coreConnection.getTypeMap();
        }

        @Override
        public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
            coreConnection.setTypeMap(map);
        }

        @Override
        public void setHoldability(int holdability) throws SQLException {
            coreConnection.setHoldability(holdability);
        }

        @Override
        public int getHoldability() throws SQLException {
            return coreConnection.getHoldability();
        }

        @Override
        public Savepoint setSavepoint() throws SQLException {
            return coreConnection.setSavepoint();
        }

        @Override
        public Savepoint setSavepoint(String name) throws SQLException {
            return coreConnection.setSavepoint(name);
        }

        @Override
        public void rollback(Savepoint savepoint) throws SQLException {
            coreConnection.rollback();
        }

        @Override
        public void releaseSavepoint(Savepoint savepoint) throws SQLException {
            coreConnection.releaseSavepoint(savepoint);
        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency,
                                         int resultSetHoldability) throws SQLException {
            return coreConnection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
                                                  int resultSetHoldability) throws SQLException {
            return coreConnection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
                                             int resultSetHoldability) throws SQLException {
            return coreConnection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
            return coreConnection.prepareStatement(sql, autoGeneratedKeys);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
            return coreConnection.prepareStatement(sql, columnIndexes);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
            return coreConnection.prepareStatement(sql, columnNames);
        }

        @Override
        public Clob createClob() throws SQLException {
            return coreConnection.createClob();
        }

        @Override
        public Blob createBlob() throws SQLException {
            return coreConnection.createBlob();
        }

        @Override
        public NClob createNClob() throws SQLException {
            return coreConnection.createNClob();
        }

        @Override
        public SQLXML createSQLXML() throws SQLException {
            return coreConnection.createSQLXML();
        }

        @Override
        public boolean isValid(int timeout) throws SQLException {
            return coreConnection.isValid(timeout);
        }

        @Override
        public void setClientInfo(String name, String value) throws SQLClientInfoException {
            coreConnection.setClientInfo(name, value);
        }

        @Override
        public void setClientInfo(Properties properties) throws SQLClientInfoException {
            coreConnection.setClientInfo(properties);
        }

        @Override
        public String getClientInfo(String name) throws SQLException {
            return coreConnection.getClientInfo(name);
        }

        @Override
        public Properties getClientInfo() throws SQLException {
            return coreConnection.getClientInfo();
        }

        @Override
        public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
            return coreConnection.createArrayOf(typeName, elements);
        }

        @Override
        public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
            return coreConnection.createStruct(typeName, attributes);
        }

        @Override
        public void setSchema(String schema) throws SQLException {
            coreConnection.setSchema(schema);
        }

        @Override
        public String getSchema() throws SQLException {
            return coreConnection.getSchema();
        }

        @Override
        public void abort(Executor executor) throws SQLException {
            coreConnection.abort(executor);
        }

        @Override
        public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
            coreConnection.setNetworkTimeout(executor, milliseconds);
        }

        @Override
        public int getNetworkTimeout() throws SQLException {
            return coreConnection.getNetworkTimeout();
        }

        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            return coreConnection.unwrap(iface);
        }

        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            return coreConnection.isWrapperFor(iface);
        }
    }

    private MyConnectionPool() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < MAX_CONNECTIONS; i++) {
            inActiveConnections.addElement(new MyConnection(getUnpooledConnection()));
        }
    }

    public static MyConnectionPool getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private Connection getUnpooledConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    private synchronized void pushback(MyConnection connection) {
        if (connection != null) {
            if (activeConnections.removeElement(connection)) {
                inActiveConnections.addElement(connection);
            } else {
                throw new NullPointerException("Connection is not inactive");
            }
        }
    }

    @Override
    public synchronized Connection getConnection() throws SQLException {
        MyConnection newConn = null;
        if (inActiveConnections.size() == 0) {
            newConn = new MyConnection(getUnpooledConnection());
        } else {
            newConn = (MyConnection) inActiveConnections.lastElement();
            inActiveConnections.removeElement(newConn);
        }
        activeConnections.addElement(newConn);
        return newConn;
    }
}
